/*
 * @Author: wupeiwen <javapeiwen2010@gmail.com>
 * @Date: 2022-04-11 11:29:18
 * @LastEditors: wupeiwen <javapeiwen2010@gmail.com>
 * @LastEditTime: 2023-06-30 15:39:23
 * @FilePath: /tea-garden-web/src/util/storeModules/farming-calendar.js
 * @Description: 农事计划
 */
import { get, post } from '@/util/http.js'
import { DateTime, Duration } from 'luxon'
import { months, weekDays } from '@/util/dict.js'
import { ElMessage } from 'element-plus'
import { massifData } from '@/util/resData'

export default {
  state: {
    // 地块查询
    query: '',
    // 当前日期
    dateNow: '',
    // 日历周期
    dateRange: [],
    // 地块
    farmlands: [],
    // 农事类型颜色
    legendColors: ['#1FD1A5', '#FEAD54', '#369BFF', '#FF7EA8', '#906BFF', '#59DD7E', '#636E95', '#AFB5CA', '#D46E6E'],
    // 农事类型过滤值
    farmingFilters: [],
    // 全部的农事计划
    allFarmingPlans: [],
    // 单一地块的农事计划
    farmingPlans: [],
    // 农事计划详情
    farmingPlanDetail: null,
    // 加载中
    loading: {
      farmlands: false,
      allFarmingPlans: false,
      farmingPlans: false,
      farmingPlanDetail: false
    }
  },
  getters: {
    calendarContent: (state) => {
      const calendarTable = {}
      // eslint-disable-next-line camelcase
      state.farmlands.map(({ massifId }) => {
        calendarTable[massifId] = new Array(12).fill('')
        calendarTable[massifId] = calendarTable[massifId].map(() => {
          return []
        })
        return ''
      })
      // eslint-disable-next-line camelcase
      state.allFarmingPlans.map(({ farmingType, massifNum, massifId, planTime, groupUser }) => {
        const dateIndex = state.dateRange.findIndex(({ date }) => {
          // eslint-disable-next-line camelcase
          return date === planTime
        })
        // console.log(dateIndex)
        // console.log(massifId)
        if (dateIndex > -1) {
          calendarTable[massifId][dateIndex].push(Object.assign({}, { farmingType, massifId, massifNum, planTime, groupUser }))
        }
        return ''
      })
      return calendarTable
    }
  },
  mutations: {
    // 设置地块查询
    setQuery (state, payload) {
      state.query = payload
    },
    // 设置日历日期周期
    setDateRange (state, payload) {
      if (payload) {
        payload = DateTime.fromISO(payload)
      } else {
        payload = DateTime.now()
      }
      state.dateNow = payload.toISODate()
      const array = []
      for (let index = 0; index < 12; index++) {
        const dur = Duration.fromObject({ days: -2 + index })
        const dt = payload.plus(dur)
        array[index] = { date: dt.toISODate(), month: months[dt.month], day: dt.day, weekDay: weekDays[dt.weekday] }
      }
      state.dateRange = array
    },
    // 设置农事类型过滤
    setFarmingFilters (state, payload) {
      const farmingFilters = state.farmingFilters
      const index = farmingFilters.findIndex((item) => {
        return item === payload.id
      })
      if (index === -1) {
        farmingFilters.push(payload.id)
      } else {
        farmingFilters.splice(index, 1)
      }
      state.farmingFilters = farmingFilters
    },
    // 设置通用状态
    setCommonState (state, payload) {
      const { key, value } = payload
      state[key] = value
    },
    // 设置加载状态
    setLoadingState (state, payload) {
      const { key, value } = payload
      state.loading[key] = value
    }
  },
  actions: {
    // 获取地块
    async getFarmlands ({ commit }) {
      try {
        commit('setLoadingState', { key: 'farmlands', value: true })
        commit('setCommonState', { key: 'farmlands', value: [] })
        // const { data } = await get({ url: '/Farming/GetMassifList' })
        // const { data } = massifData
        // commit('setCommonState', { key: 'farmlands', value: data.sort((a, b) => { return Number(a.massifId) - Number(b.massifId) }) })
        const { data } = await get({ url: '/land/list' })
        data.map(async item => {
          item.massifId = item.id
        })
        commit('setCommonState', { key: 'farmlands', value: data.sort((a, b) => { return Number(a.massifId) - Number(b.massifId) }) })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'farmlands', value: false })
    },
    // 获取时间区间内所有地块的农事计划
    async getAllFarmingPlans ({ state, commit }) {
      try {
        commit('setLoadingState', { key: 'allFarmingPlans', value: true })
        commit('setCommonState', { key: 'allFarmingPlans', value: [] })
        if (state.dateRange.length === 0) {
          commit('setDateRange')
        }
        // const { data } = await post({ url: '/Farming/FarmingPlanList', params: { start_time: state.dateRange[0].date, end_time: state.dateRange.slice(-1)[0].date, farming_type: state.farmingFilters } })
        const { data } = await get({ url: `/farming/calendarList?farmingType=${state.farmingFilters}&time1=${state.dateRange[0].date}&time2=${state.dateRange.slice(-1)[0].date}` })
        commit('setCommonState', { key: 'allFarmingPlans', value: data })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'allFarmingPlans', value: false })
    },
    // 获取单一地块某日的农事计划
    async getFarmingPlans ({ commit }, payload) {
      try {
        commit('setLoadingState', { key: 'farmingPlans', value: true })
        commit('setCommonState', { key: 'farmingPlans', value: [] })
        const { data } = await get({ url: '/farming/detail', params: { planTime: payload.planTime, massifId: payload.massifId } })
        commit('setCommonState', { key: 'farmingPlans', value: data })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'farmingPlans', value: false })
    },
    // 获取某一农事计划的详情
    async getFarmingPlanDetail ({ commit }, payload) {
      try {
        commit('setLoadingState', { key: 'farmingPlanDetail', value: true })
        commit('setCommonState', { key: 'farmingPlanDetail', value: null })
        const { data } = await get({ url: '/Farming/GetPlanDetail', params: { id: payload } })
        commit('setCommonState', { key: 'farmingPlanDetail', value: data })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'farmingPlanDetail', value: false })
    },
    // 新增农事计划
    async AddFarmingPlan ({ dispatch }, payload) {
      console.log(payload, 'vuex请求')
      try {
        let code, message
        // 采摘3、施肥4、灌溉5、病虫害9、防霜冻10
        if (payload.farmingType === 4) {
          const res = await post({ url: '/fertilizing/add', params: { ...payload } })
          code = res.code
          message = res.message
        } else if (payload.farmingType === 5) {
          const res = await post({ url: '/irrigation/add', params: { ...payload } })
          code = res.code
          message = res.message
        } else if (payload.farmingType === 3) {
          const res = await post({ url: '/harvest/add', params: { ...payload } })
          code = res.code
          message = res.message
        } else if (payload.farmingType === 9) {
          const res = await post({ url: '/pestControl/add', params: { ...payload } })
          code = res.code
          message = res.message
        } else if (payload.farmingType === 9) {
          const res = await post({ url: '/frostProtection/add', params: { ...payload } })
          code = res.code
          message = res.message
        }
        // const { code, message } = await post({ url: '/Farming/AddFarmingPlan', params: { ...payload } })
        if (code === 1) {
          ElMessage({ message, type: 'success' })
        } else {
          ElMessage({ message, type: 'warning' })
        }
        dispatch('getAllFarmingPlans')
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑农事计划
    async EditFarmingPlan ({ dispatch }, payload) {
      try {
        await post({ url: '/Farming/EditFarmingPlan', params: { id: payload } })
        dispatch('getAllFarmingPlans')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
